<template>
  <div class="title-check-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <h2>论文题目查重</h2>
      <p>检查您的论文题目是否与已有论文重复，避免选题冲突</p>
    </div>

    <el-row :gutter="24">
      <!-- 查重表单 -->
      <el-col :lg="14" :md="16" :sm="24">
        <el-card class="check-form-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon size="20" color="#409EFF">
                <Document />
              </el-icon>
              <span>提交题目查重</span>
            </div>
          </template>

          <el-form
            ref="checkFormRef"
            :model="checkForm"
            :rules="checkRules"
            label-width="100px"
            @submit.prevent="handleSubmit"
          >
            <el-form-item label="论文题目" prop="title">
              <el-input
                v-model="checkForm.title"
                type="textarea"
                :rows="3"
                placeholder="请输入您的论文题目"
                maxlength="200"
                show-word-limit
                clearable
              />
            </el-form-item>

            <el-form-item label="查重范围" prop="checkScope">
              <el-radio-group v-model="checkForm.checkScope">
                <el-radio label="current">本届毕业生</el-radio>
                <el-radio label="history">历史毕业生</el-radio>
                <el-radio label="current_and_history">本届+历史</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="历史年份" prop="yearRange" v-if="checkForm.checkScope !== 'current'">
              <el-slider
                v-model="checkForm.yearRange"
                :min="1"
                :max="10"
                :marks="yearMarks"
                show-tooltip
              />
            </el-form-item>

            <el-form-item label="论文描述" prop="description">
              <el-input
                v-model="checkForm.description"
                type="textarea"
                :rows="2"
                placeholder="请简要描述您的论文内容和研究方向（可选）"
                maxlength="500"
                show-word-limit
              />
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                size="large"
                :loading="checking"
                @click="handleSubmit"
              >
                <el-icon><Search /></el-icon>
                {{ checking ? '查重中...' : '开始查重' }}
              </el-button>
              <el-button size="large" @click="resetForm">
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <!-- 查重提示 -->
      <el-col :lg="10" :md="8" :sm="24">
        <el-card class="tips-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon size="20" color="#E6A23C">
                <InfoFilled />
              </el-icon>
              <span>查重说明</span>
            </div>
          </template>

          <div class="tips-content">
            <el-alert
              title="温馨提示"
              type="info"
              :closable="false"
              show-icon
            />

            <div class="tip-list">
              <div class="tip-item">
                <el-icon color="#67C23A"><SuccessFilled /></el-icon>
                <span>题目重复率低于15%为安全范围</span>
              </div>
              <div class="tip-item">
                <el-icon color="#E6A23C"><WarningFilled /></el-icon>
                <span>重复率15%-30%需要调整题目</span>
              </div>
              <div class="tip-item">
                <el-icon color="#F56C6C"><CircleCloseFilled /></el-icon>
                <span>重复率高于30%建议重新选题</span>
              </div>
            </div>

            <el-divider />

            <div class="suggestion-list">
              <h4>选题建议：</h4>
              <ul>
                <li>避免使用过于宽泛的题目</li>
                <li>结合当前技术热点和发展趋势</li>
                <li>考虑加入具体的应用场景</li>
                <li>适当添加创新点和特色</li>
              </ul>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 查重结果 -->
    <div v-if="checkResult" class="result-section">
      <ResultCard
        :type="getResultType(checkResult.riskLevel)"
        :icon="getResultIcon(checkResult.riskLevel)"
        :title="`题目查重完成 - ${getRiskLevelText(checkResult.riskLevel)}`"
        :subtitle="`最高相似度: ${checkResult.maxSimilarity}%`"
        :main-value="checkResult.maxSimilarity"
        unit="%"
        :description="`发现 ${checkResult.duplicateCount} 个相似题目`"
        :tags="getResultTags(checkResult)"
        :details="getResultDetails(checkResult)"
        :show-progress="true"
        :progress-label="'相似度'"
        :progress-value="checkResult.maxSimilarity"
        :progress-status="getProgressStatus(checkResult.riskLevel)"
        :actions="resultActions"
        @action="handleResultAction"
      />

      <!-- 相似题目列表 -->
      <el-card v-if="checkResult.duplicateResults && checkResult.duplicateResults.length > 0" class="similar-titles-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <el-icon size="20" color="#F56C6C">
              <Files />
            </el-icon>
            <span>相似题目列表</span>
            <el-tag :type="getResultType(checkResult.riskLevel)">
              共 {{ checkResult.duplicateResults.length }} 个
            </el-tag>
          </div>
        </template>

        <div class="similar-list">
          <div
            v-for="(item, index) in checkResult.duplicateResults"
            :key="index"
            class="similar-item"
          >
            <div class="similarity-badge">
              <el-progress
                type="circle"
                :percentage="item.similarity"
                :width="60"
                :stroke-width="6"
                :status="getSimilarityStatus(item.similarity)"
              />
            </div>
            <div class="similar-content">
              <h4 class="similar-title">{{ item.title }}</h4>
              <div class="similar-meta">
                <el-tag size="small" type="info">{{ item.author }}</el-tag>
                <el-tag size="small" type="">{{ item.className }}</el-tag>
                <el-tag size="small" type="warning">{{ item.year }}年</el-tag>
              </div>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 修改建议 -->
      <el-card v-if="checkResult.suggestions && checkResult.suggestions.length > 0" class="suggestions-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <el-icon size="20" color="#409EFF">
              <Warning />
            </el-icon>
            <span>修改建议</span>
          </div>
        </template>

        <div class="suggestions-list">
          <div
            v-for="(suggestion, index) in checkResult.suggestions"
            :key="index"
            class="suggestion-item"
          >
            <el-icon color="#409EFF"><Check /></el-icon>
            <span>{{ suggestion }}</span>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 查重历史 -->
    <el-card class="history-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <el-icon size="20" color="#909399">
            <Clock />
          </el-icon>
          <span>查重历史</span>
          <el-button type="text" @click="refreshHistory">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </template>

      <DataTable
        :data="historyData"
        :columns="historyColumns"
        :loading="historyLoading"
        :pagination="historyPagination"
        :show-selection="false"
        :show-index="true"
        empty-text="暂无查重记录"
        @page-change="handleHistoryPageChange"
        @action="handleHistoryAction"
      />
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import {
  Document,
  InfoFilled,
  SuccessFilled,
  WarningFilled,
  CircleCloseFilled,
  Search,
  Files,
  Warning,
  Check,
  Clock,
  Refresh,
  View,
  Download
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAppStore } from '@/stores/app'
import { useUserStore } from '@/stores/user'
import { submitTitleCheck, getTitleCheckHistory } from '@/api/student'
import { RISK_LEVEL_CONFIG } from '@/utils/constants'
import { formatDateTime } from '@/utils'
import ResultCard from '@/components/ResultCard.vue'
import DataTable from '@/components/DataTable.vue'

const appStore = useAppStore()
const userStore = useUserStore()
const router = useRouter()

// 表单引用
const checkFormRef = ref()

// 查重状态
const checking = ref(false)

// 查重表单
const checkForm = reactive({
  title: '',
  checkScope: 'current_and_history',
  yearRange: 5,
  description: ''
})

// 年份标记
const yearMarks = {
  1: '1年',
  3: '3年',
  5: '5年',
  10: '10年'
}

// 表单验证规则
const checkRules = {
  title: [
    { required: true, message: '请输入论文题目', trigger: 'blur' },
    { min: 10, message: '题目长度至少10个字符', trigger: 'blur' },
    { max: 200, message: '题目长度不能超过200个字符', trigger: 'blur' }
  ],
  checkScope: [
    { required: true, message: '请选择查重范围', trigger: 'change' }
  ]
}

// 查重结果
const checkResult = ref(null)

// 结果操作按钮
const resultActions = [
  { key: 'view-detail', label: '查看详情', type: 'primary', icon: View },
  { key: 'download-report', label: '下载报告', type: 'default', icon: Download }
]

// 历史记录
const historyData = ref([])
const historyLoading = ref(false)
const historyPagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 历史记录表格列
const historyColumns = [
  {
    prop: 'title',
    label: '论文题目',
    minWidth: 200,
    showOverflowTooltip: true
  },
  {
    prop: 'maxSimilarity',
    label: '最高相似度',
    width: 120,
    formatter: (value) => `${value}%`
  },
  {
    prop: 'duplicateCount',
    label: '相似数量',
    width: 100
  },
  {
    prop: 'riskLevel',
    label: '风险等级',
    width: 100,
    type: 'tag',
    tagMap: {
      low: { label: '低风险', type: 'success' },
      medium: { label: '中风险', type: 'warning' },
      high: { label: '高风险', type: 'danger' }
    }
  },
  {
    prop: 'checkTime',
    label: '查重时间',
    width: 180,
    formatter: (value) => formatDateTime(value)
  },
  {
    type: 'action',
    label: '操作',
    width: 120,
    actions: [
      { key: 'view', label: '查看', type: 'primary' },
      { key: 'recheck', label: '重新查重', type: 'success' }
    ]
  }
]

// 改进的认证检查方法
const checkUserAuth = () => {
  try {
    // 首先检查 store 中的 token
    let token = userStore.token
    let userInfo = userStore.userInfo
    
    // 如果 store 中没有，检查本地存储
    if (!token) {
      token = localStorage.getItem('token') || sessionStorage.getItem('token')
      console.log('🔐 从本地存储获取token:', token ? '存在' : '不存在')
    }
    
    if (!userInfo) {
      const storedUserInfo = localStorage.getItem('userInfo') || sessionStorage.getItem('userInfo')
      if (storedUserInfo) {
        try {
          userInfo = JSON.parse(storedUserInfo)
          console.log('🔐 从本地存储解析用户信息成功')
        } catch (e) {
          console.error('解析本地存储的用户信息失败:', e)
        }
      }
    }
    
    // 如果本地存储中有但 store 中没有，同步到 store
    if (token && !userStore.token) {
      userStore.login(token, userInfo)
      console.log('🔄 从本地存储同步认证信息到store')
    }
    
    // 最终检查
    const finalToken = userStore.token || token
    const finalUserInfo = userStore.userInfo || userInfo
    
    console.log('🔐 最终认证检查:', {
      token: finalToken ? '存在' : '不存在',
      userInfo: finalUserInfo ? '存在' : '不存在',
      userType: finalUserInfo?.userType
    })
    
    if (!finalToken) {
      console.warn('❌ 认证失败: 未找到token')
      return false
    }
    
    if (finalUserInfo?.userType !== 'S') {
      console.warn('❌ 认证失败: 用户角色不是学生')
      return false
    }
    
    console.log('✅ 认证成功: 用户已登录且角色正确')
    return true
    
  } catch (error) {
    console.error('❌ 认证检查过程中发生错误:', error)
    return false
  }
}

// 处理未认证情况
const handleUnauthenticated = (message = '请先登录系统') => {
  ElMessage.warning(message)
  
  // 显示确认对话框
  ElMessageBox.confirm('您尚未登录或登录已过期，是否前往登录页面？', '登录提示', {
    confirmButtonText: '前往登录',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 跳转到登录页
    router.push('/login')
  }).catch(() => {
    // 用户取消，不做操作
    console.log('用户取消登录跳转')
  })
  
  return false
}

// 改进的提交查重方法
const handleSubmit = async () => {
  if (!checkFormRef.value) return
  
  try {
    await checkFormRef.value.validate()
    
    // 检查认证状态
    if (!checkUserAuth()) {
      handleUnauthenticated()
      return
    }
    
    checking.value = true
    checkResult.value = null // 清除之前的结果
    
    ElMessage.info('🚀 正在启动题目查重...')
    
    // 准备请求数据
    const requestData = {
      title: checkForm.title,
      checkScope: checkForm.checkScope,
      yearRange: checkForm.checkScope === 'current' ? 0 : checkForm.yearRange,
      description: checkForm.description || ''
    }
    
    console.log('📤 提交查重请求:', requestData)
    
    // 调用API
    const response = await submitTitleCheck(requestData)
    
    // 根据后端响应格式调整
    if (response.code === 200) {
      checkResult.value = response.data
      ElMessage.success('✅ 题目查重完成！结果已在下方显示')
      
      // 刷新历史记录
      await loadHistory()
      
      // 滚动到结果区域
      setTimeout(() => {
        const resultElement = document.querySelector('.result-section')
        if (resultElement) {
          resultElement.scrollIntoView({ behavior: 'smooth', block: 'start' })
        }
      }, 300)
    } else {
      throw new Error(response.message || '查重失败')
    }
    
  } catch (error) {
    console.error('题目查重失败:', error)
    
    // 更详细的错误处理
    if (error.response?.status === 401) {
      handleUnauthenticated('登录已过期，请重新登录')
      userStore.logout()
    } else if (error.response?.status === 403) {
      ElMessage.error('权限不足，无法执行此操作')
    } else if (error.response?.status === 400) {
      ElMessage.error(`请求参数错误: ${error.response.data?.message || error.message}`)
    } else if (error.code === 'NETWORK_ERROR' || !navigator.onLine) {
      ElMessage.error('网络连接失败，请检查网络后重试')
    } else {
      ElMessage.error(`查重失败: ${error.message || '服务器错误，请稍后重试'}`)
    }
  } finally {
    checking.value = false
  }
}

// 重置表单
const resetForm = () => {
  if (checkFormRef.value) {
    checkFormRef.value.resetFields()
    // 重置为默认值
    checkForm.checkScope = 'current_and_history'
    checkForm.yearRange = 5
    checkForm.description = ''
  }
  checkResult.value = null
}

// 获取结果类型
const getResultType = (riskLevel) => {
  const typeMap = {
    low: 'success',
    medium: 'warning',
    high: 'danger'
  }
  return typeMap[riskLevel] || 'info'
}

// 获取结果图标
const getResultIcon = (riskLevel) => {
  const iconMap = {
    low: SuccessFilled,
    medium: WarningFilled,
    high: CircleCloseFilled
  }
  return iconMap[riskLevel] || InfoFilled
}

// 获取风险等级文本
const getRiskLevelText = (riskLevel) => {
  return RISK_LEVEL_CONFIG[riskLevel]?.label || '未知风险'
}

// 获取进度条状态
const getProgressStatus = (riskLevel) => {
  const statusMap = {
    low: 'success',
    medium: 'warning',
    high: 'exception'
  }
  return statusMap[riskLevel]
}

// 获取相似度状态
const getSimilarityStatus = (similarity) => {
  if (similarity < 15) return 'success'
  if (similarity < 30) return 'warning'
  return 'exception'
}

// 获取结果标签
const getResultTags = (result) => {
  const tags = []
  if (result.checkScope === 'current') {
    tags.push({ label: '本届查重', type: 'info' })
  } else if (result.checkScope === 'history') {
    tags.push({ label: '历史查重', type: 'info' })
  } else {
    tags.push({ label: '全面查重', type: 'primary' })
  }
  
  if (result.yearRange) {
    tags.push({ label: `${result.yearRange}年范围`, type: 'default' })
  }
  
  return tags
}

// 获取结果详情
const getResultDetails = (result) => {
  return [
    { label: '平均相似度', value: `${result.avgSimilarity || 0}%` },
    { label: '相似论文数', value: result.duplicateCount || 0 },
    { label: '查重时间', value: formatDateTime(result.checkTime) }
  ]
}

// 结果操作处理
const handleResultAction = (actionKey) => {
  switch (actionKey) {
    case 'view-detail':
      ElMessage.info('查看详细结果功能开发中...')
      break
    case 'download-report':
      ElMessage.info('下载报告功能开发中...')
      break
  }
}

// 改进的加载历史记录方法
const loadHistory = async () => {
  try {
    historyLoading.value = true
    
    // 检查认证状态
    if (!checkUserAuth()) {
      console.warn('加载历史记录失败: 用户未认证')
      historyData.value = []
      historyPagination.total = 0
      return
    }
    
    console.log('📖 加载历史记录，页码:', historyPagination.current, '大小:', historyPagination.size)
    
    // 调用API获取历史记录
    const response = await getTitleCheckHistory({
      page: historyPagination.current,
      size: historyPagination.size
    })
    
    if (response.code === 200) {
      // 根据后端分页响应格式调整
      const pageData = response.data
      
      // 处理不同的分页响应格式
      if (pageData && typeof pageData === 'object') {
        // PageInfo 格式
        if (pageData.list) {
          historyData.value = pageData.list
          historyPagination.total = pageData.total || 0
        } 
        // Spring Data 格式
        else if (pageData.content) {
          historyData.value = pageData.content
          historyPagination.total = pageData.totalElements || 0
        }
        // 其他格式
        else {
          historyData.value = Array.isArray(pageData) ? pageData : []
          historyPagination.total = historyData.value.length
        }
      } else {
        historyData.value = []
        historyPagination.total = 0
      }
      
      console.log(`✅ 成功加载 ${historyData.value.length} 条历史记录，总数: ${historyPagination.total}`)
    } else {
      throw new Error(response.message || '获取历史记录失败')
    }
    
  } catch (error) {
    console.error('加载历史记录失败:', error)
    
    if (error.response?.status === 401) {
      handleUnauthenticated('登录已过期，无法查看历史记录')
      userStore.logout()
    } else if (error.response?.status === 403) {
      ElMessage.error('权限不足，无法查看历史记录')
    } else if (error.response?.status === 400) {
      ElMessage.error(`获取历史记录失败: ${error.response.data?.message || error.message}`)
    } else {
      // 网络错误或其他错误，显示空数据
      historyData.value = []
      historyPagination.total = 0
      console.warn('历史记录加载失败，显示空数据:', error.message)
      
      // 只在非认证错误时显示提示
      if (error.response?.status !== 401 && error.response?.status !== 403) {
        ElMessage.error('加载历史记录失败，请稍后重试')
      }
    }
  } finally {
    historyLoading.value = false
  }
}

// 刷新历史
const refreshHistory = () => {
  historyPagination.current = 1
  loadHistory()
}

// 历史分页变化
const handleHistoryPageChange = (page) => {
  historyPagination.current = page
  loadHistory()
}

// 历史操作处理
const handleHistoryAction = (actionKey, row) => {
  switch (actionKey) {
    case 'view':
      ElMessage.info(`查看记录: ${row.title}`)
      // 可以在这里实现查看详情的逻辑
      break
    case 'recheck':
      // 重新查重逻辑
      checkForm.title = row.title
      handleSubmit()
      break
  }
}

// 页面加载
onMounted(() => {
  appStore.setPageTitle('题目查重')
  appStore.setBreadcrumbs([
    { title: '学生中心', path: '/student' },
    { title: '题目查重', path: '/student/title-check' }
  ])
  
  console.log('🚀 题目查重页面加载完成')
  
  // 检查初始认证状态
  const isAuthenticated = checkUserAuth()
  
  if (!isAuthenticated) {
    console.warn('页面加载时检测到用户未认证，等待用户操作时再提示')
    // 不立即跳转，等用户操作时再提示，提供更好的用户体验
  } else {
    // 加载历史记录
    loadHistory()
  }
})
</script>

<style scoped>
.title-check-container {
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 24px;
  text-align: center;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
}

.check-form-card,
.tips-card,
.history-card,
.similar-titles-card,
.suggestions-card {
  margin-bottom: 24px;
  border-radius: 12px;
  border: none;
}

/* 提示卡片 */
.tips-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.tip-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.tip-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #606266;
}

.suggestion-list h4 {
  margin: 0 0 12px 0;
  color: #303133;
  font-size: 14px;
}

.suggestion-list ul {
  margin: 0;
  padding-left: 20px;
  color: #606266;
  font-size: 14px;
  line-height: 1.6;
}

/* 结果部分 */
.result-section {
  margin: 32px 0;
}

/* 相似题目列表 */
.similar-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.similar-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #F56C6C;
}

.similarity-badge {
  flex-shrink: 0;
}

.similar-content {
  flex: 1;
  min-width: 0;
}

.similar-title {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 500;
  word-break: break-all;
}

.similar-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

/* 建议列表 */
.suggestions-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.suggestion-item {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  color: #606266;
  font-size: 14px;
  line-height: 1.6;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .similar-item {
    flex-direction: column;
    align-items: stretch;
    text-align: center;
  }
  
  .similar-meta {
    justify-content: center;
  }
}
</style>